﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using DG.Tweening;

public class DragUI : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
    public enum OperatorType {
        Jam,
        Cream,
        Decoration,
    }

    [SerializeField]
    Camera _camera;

    [SerializeField]
    float _distanceToCamera = -12f;

    [SerializeField]
    OperatorType _operatorType = OperatorType.Jam;

    bool _canDrag;
    ScrollRect _scrollRect;

    static LevelDecorating _levelDecorating;
    PaoFuController _paofuController;
    Transform _target;

    void Start() {
        _scrollRect = GetComponentInParent<ScrollRect>();
        
        if (_levelDecorating == null) {
            _levelDecorating = GetComponentInParent<LevelDecorating>();
        }
	}
	
	void Update() {
        if (_target == null) {
            return;
        }

		if (Input.GetMouseButton(0)) {
            //if (!IsOverUI() && _canDrag) {
            if (_canDrag) {
                var z = _camera.WorldToScreenPoint(_levelDecorating.parent.position).z - _distanceToCamera;
                Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;

                switch (_operatorType) {
                    case OperatorType.Jam:
                        if (Physics.Raycast(ray, out hit)) {
                            _target.DOLocalRotate(Vector3.up * 135f, 0.5f).OnComplete(() => {
                                _levelDecorating.SelectJam(name);
                            });
                        } else {
                            _target.DOLocalRotate(Vector3.up * 30f, 0.5f);
                        }

                        _target.position = _camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, z));
                        break;
                    case OperatorType.Cream:
                        if (Physics.Raycast(ray, out hit)) {
                            _target.position = hit.point;

                            if (CakeShopManager.Instance.CurrentCakeType.Equals(CakeType.PaoFu)) {
                                _paofuController = hit.transform.GetComponent<PaoFuController>();

                                if (_paofuController) {
                                    _paofuController.OnEnter();
                                }
                            }
                        } else {
                            _target.position = _camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, z));

                            if (CakeShopManager.Instance.CurrentCakeType.Equals(CakeType.PaoFu)) {
                                if (_paofuController) {
                                    _paofuController.OnExit();
                                }
                            }
                        }
                        break;
                    case OperatorType.Decoration:
                        if (Physics.Raycast(ray, out hit)) {
                            if (CakeShopManager.Instance.CurrentCakeType.Equals(CakeType.MiCai)) {
                                if (hit.transform.name.Contains("MiCai")) {
                                    _target.DOLocalRotate(Vector3.up * 30f, 0.5f);
                                    _target.Find("Effect").SetActive(false);
                                    _target.position = _camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, z));
                                    return;
                                }

                                _target.DOLocalRotate(Vector3.up * 150f, 0.5f).OnComplete(() => {
                                    _target.Find("Effect").SetActive(true);
                                });
                            }

                            _target.position = hit.point;
                        } else {
                            _target.position = _camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, z));

                            if (CakeShopManager.Instance.CurrentCakeType.Equals(CakeType.MiCai)) {
                                _target.DOLocalRotate(Vector3.up * 30f, 0.5f);
                                _target.Find("Effect").SetActive(false);
                            }
                        }
                        break;
                }
            }
        } else if (Input.GetMouseButtonUp(0)) {
            Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            var endPos = transform.position + (transform.forward * -10f);

            switch (_operatorType) {
                case OperatorType.Jam:
                    AudioManager.Instance.PlaySound(CakeShopResPath.SE_604010402);
                    _target.DOLocalRotate(Vector3.up * 30f, 0.5f);
                    _target.DOMove(endPos, 0.5f).OnComplete(() => {
                        Destroy(_target.gameObject);
                        _lastPointerDrag.enabled = true;
                    });
                    break;
                case OperatorType.Cream:
                    if (Physics.Raycast(ray, out hit)) {
                        if (CakeShopManager.Instance.CurrentCakeType.Equals(CakeType.PaoFu)) {
                            if (_paofuController) {
                                _paofuController.ShowCream(_levelDecorating.CurrentCreamColor, () => {
                                    if (PaoFuController.IsShowButton) {
                                        _levelDecorating.ActiveButton();
                                    }
                                });

                                _levelDecorating.DisableHandMove();
                                _paofuController = null;
                            }
                        } else {
                            if (_levelDecorating.CurrentCreamModel == null) {
                                _levelDecorating.SwitchCream();
                            }
                            
                            if (_currentCreamTexture) {
                                _levelDecorating.CurrentCreamModel.SetActive(false);
                                _levelDecorating.CurrentCreamModel.GetComponentInChildren<Renderer>().sharedMaterial.mainTexture = _currentCreamTexture;
                                _levelDecorating.CurrentCreamModel.SetActive(true);
                            }

                            _levelDecorating.ActiveButton();
                        }
                    }

                    AudioManager.Instance.PlaySound(CakeShopResPath.SE_604010402);
                    _target.DOMove(endPos, 0.5f).OnComplete(() => {
                        Destroy(_target.gameObject);
                        _lastPointerDrag.enabled = true;
                    });
                    break;
                case OperatorType.Decoration:
                    if (Physics.Raycast(ray, out hit) && _canDrag) {
                        switch (CakeShopManager.Instance.CurrentCakeType) {
                            case CakeType.MiCai:
                                AudioManager.Instance.PlaySound(CakeShopResPath.SE_604010402);
                                _target.Find("Effect").SetActive(false);
                                _target.DOLocalRotate(Vector3.up * 30f, 0.5f);
                                _target.DOMove(endPos, 0.5f).OnComplete(() => {
                                    Destroy(_target.gameObject);
                                    _lastPointerDrag.enabled = true;
                                });
                                break;
                            case CakeType.YingHua:
                                if (hit.transform.childCount > 0) {
                                    Destroy(hit.transform.GetChild(0).gameObject);
                                }

                                _target.position = hit.transform.position;
                                _target.localEulerAngles = Vector3.forward * UnityEngine.Random.Range(-120f, 30f);
                                _target.GetChild(0).localEulerAngles = new Vector3(90f, 0f, UnityEngine.Random.Range(0f, 360f));
                                _target.SetParent(hit.transform);
                                _lastPointerDrag.enabled = true;
                                _target = null;
                                break;
                            default:
                                _target.position = hit.point;
                                _lastPointerDrag.enabled = true;
                                _target = null;
                                break;
                        }

                        _levelDecorating.ActiveButton();
                    } else {
                        AudioManager.Instance.PlaySound(CakeShopResPath.SE_604010402);
                        _target.DOMove(endPos, 0.5f).OnComplete(() => {
                            Destroy(_target.gameObject);
                            _lastPointerDrag.enabled = true;
                        });
                    }

                    break;
            }

            _canDrag = false;
        }
	}

    static Texture2D _currentCreamTexture;

    public void OnBeginDrag(PointerEventData eventData) {
        _scrollRect.OnBeginDrag(eventData);
        AutoScroll.IsEnabled = false;

        if (_operatorType.Equals(OperatorType.Cream)) {
            _levelDecorating.SwitchCollider();

            switch (name) {
                case "CreamBottle_White":
                    _levelDecorating.CurrentCreamColor = CreamColor.White;
                    _currentCreamTexture = CommonUtility.LoadTexture(CakeShopResPath.CREAM_WHITE);
                    break;
                case "CreamBottle_Pink":
                    _levelDecorating.CurrentCreamColor = CreamColor.Pink;
                    _currentCreamTexture = CommonUtility.LoadTexture(CakeShopResPath.CREAM_PINK);
                    break;
                case "CreamBottle_Blue":
                    _levelDecorating.CurrentCreamColor = CreamColor.Blue;
                    _currentCreamTexture = CommonUtility.LoadTexture(CakeShopResPath.CREAM_BLUE);
                    break;
                case "CreamBottle_Orange":
                    _levelDecorating.CurrentCreamColor = CreamColor.Orange;
                    _currentCreamTexture = CommonUtility.LoadTexture(CakeShopResPath.CREAM_ORANGE);
                    break;
            }
        }
    }

    Image _lastPointerDrag;

    public void OnDrag(PointerEventData eventData) {
        _scrollRect.OnDrag(eventData);

        if (eventData.delta.x <= -15f && _canDrag == false) {
            _canDrag = true;
            _scrollRect.enabled = false;

            if (_target == null) {
                _target = CommonUtility.InstantiateFrom(CakeShopResPath.PREFAB_DIR + name, _levelDecorating.parent);
                _lastPointerDrag = eventData.pointerDrag.GetComponent<Image>();
                _lastPointerDrag.enabled = false;
            }
        }
    }

    public void OnEndDrag(PointerEventData eventData) {
        _scrollRect.enabled = true;
        _scrollRect.OnEndDrag(eventData);
    }

    public bool IsOverUI() {
        if (Input.GetMouseButton(0) 
            || Input.GetMouseButtonUp(0)
            || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)) {
#if !UNITY_EDITOR && (UNITY_IOS || UNITY_ANDROID)
			if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) {
#else
            if (EventSystem.current.IsPointerOverGameObject()) {
#endif
                //Debug.Log("当前触摸在UI上");
                return true;
            } else {
                //Debug.Log("当前没有触摸在UI上");
                return false;
            }
        }

        return false;
    }
}
